package com.open.capacity.user.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.open.capacity.commons.CodeEnum;
import com.open.capacity.commons.PageResult;
import com.open.capacity.commons.Result;
import com.open.capacity.exception.BusinessException;
import com.open.capacity.finance.util.uuid.UUIDUtils;
import com.open.capacity.user.dao.SysDepartmentDao;
import com.open.capacity.user.model.SysDepartment;
import com.open.capacity.user.service.SysDepartmentService;
import com.open.capacity.user.vo.SysDepartmentVo;
import com.open.capacity.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;


@Slf4j
@Service
public class SysDepartmentServiceImpl implements SysDepartmentService {

    @Autowired
    private SysDepartmentDao departmentDao;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void save(SysDepartment sysDepartment) throws Exception {
        sysDepartment.setId(UUIDUtils.getOriginalUUIDWithoutBar());
        sysDepartment.setCreateTime(new Date());
        sysDepartment.setUpdateTime(sysDepartment.getCreateTime());

        departmentDao.save(sysDepartment);

        log.info("保存部门：{}", sysDepartment);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void update(SysDepartment sysDepartment) {
        sysDepartment.setUpdateTime(new Date());

        departmentDao.updateByOps(sysDepartment);
        log.info("修改部门：{}", sysDepartment);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(String id) throws Exception {
        SysDepartment sysDepartment = departmentDao.findById(id);

        departmentDao.delete(id);

        log.info("删除部门：{}", sysDepartment);
    }


    @Override
    public SysDepartment findById(String id) {
        return departmentDao.findById(id);
    }

    @Override
    public SysDepartment findByCode(String companyId, String code) {
        return departmentDao.findByCode(companyId, code);
    }

    @Override
    public List<SysDepartment> findDepartments(Map<String, Object> params) {
//        //设置分页信息，分别是当前页数和每页显示的总记录数【记住：必须在mapper接口中的方法执行之前设置该分页信息】
//        if (MapUtils.getInteger(params, "page") != null && MapUtils.getInteger(params, "limit") != null)
//            PageHelper.startPage(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit"), true);
        List<SysDepartment> list = departmentDao.findList(params);

        return list;
    }

    @Override
    public PageResult<SysDepartment> pageAll(Map<String, Object> params) {
        //设置分页信息，分别是当前页数和每页显示的总记录数【记住：必须在mapper接口中的方法执行之前设置该分页信息】
        if (MapUtils.getInteger(params, "page") != null && MapUtils.getInteger(params, "limit") != null)
            PageHelper.startPage(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit"), true);

        List<SysDepartment> list = departmentDao.findList(params);
        list.forEach(item -> item.setCodeAndName(item.getCode() + " " + item.getName()));
        PageInfo<SysDepartment> pageInfo = new PageInfo(list);

        return PageResult.<SysDepartment>builder().data(pageInfo.getList()).resp_code(CodeEnum.SUCCESS.getCode()).count(pageInfo.getTotal()).build();
    }

    @Override
    public List<SysDepartment> findByParentId(String parentId) {
        return departmentDao.findByParentId(parentId);
    }

    @Override
    public SysDepartment findWithInsert(String companyId, String name) {
        SysDepartment bm = departmentDao.findByName(companyId, name);
        if (bm == null) {
            bm = new SysDepartment();
            bm.setId(UUIDUtils.getOriginalUUIDWithoutBar());
            bm.setCompanyId(companyId);
            String code = getNextCode(companyId);
            bm.setCode(code);
            bm.setName(name);
            bm.setCodeAndName(code + " " + name);
            bm.setStatus(1);
            bm.setUpdateTime(new Date());
            departmentDao.save(bm);
        } else {
            bm.setCodeAndName(bm.getCode() + " " + bm.getName());
        }
        return bm;
    }

    @Override
    public String getNextCode(String companyId) {
        String code = "";
        String maxCode = departmentDao.findMaxCode(companyId);
        code = StringUtil.getNextSequence(maxCode, maxCode.length());
        return code;
    }


    @Override
    public Map<String, SysDepartmentVo> getMap() {
        Map<String, SysDepartmentVo> map = new HashMap<>();
        Map<String, Object> params = new HashMap<>();
        List<SysDepartment> list = departmentDao.findList(params);
        SysDepartmentVo vo;
        for (SysDepartment item : list) {
            vo = new SysDepartmentVo();
            vo.setCompanyId(item.getCompanyId());
            vo.setParentId(item.getParentId());
            vo.setName(item.getName());
            map.put(item.getId(), vo);
        }
        return map;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result saveOrUpdate(SysDepartment sysDepartment, String keyValue) throws Exception {
        int i = 0;
        if (sysDepartment.getParentId() == null || sysDepartment.getParentId().equals("-1") || sysDepartment.getParentId().equals("")) {
            sysDepartment.setParentId("0");
        }
        if (StringUtils.isNotEmpty(keyValue)) {
            SysDepartment model = departmentDao.findById(keyValue);
            if (model != null) {
                sysDepartment.setId(keyValue);
                sysDepartment.setUpdateTime(new Date());

                if (!sysDepartment.getStatus().equals(model.getStatus())) {
                    departmentDao.updateStatus(sysDepartment.getId(), sysDepartment.getStatus());
                }
                i = departmentDao.updateByOps(sysDepartment);
            }
        } else {
            sysDepartment.setId(UUIDUtils.getOriginalUUIDWithoutBar());
            sysDepartment.setCreateTime(new Date());
            sysDepartment.setUpdateTime(sysDepartment.getCreateTime());

            i = departmentDao.save(sysDepartment);
        }

        return i > 0 ? Result.succeed("操作成功") : Result.failed("操作失败");
    }
}
